package com.snail.workflow.service.impl;

import com.snail.common.core.utils.StringUtils;
import com.snail.workflow.api.constant.WorkflowConstants;
import com.snail.workflow.api.domain.dto.FlowProcDefDto;
import com.snail.workflow.api.domain.dto.TaskInitWorkflowDto;
import com.snail.workflow.exception.WorkflowException;
import com.snail.workflow.factory.FlowServiceFactory;
import com.snail.workflow.service.IFlowDefinitionService;
import com.snail.workflow.service.IFlowInstanceService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Description: 流程实例实现
 * @Author: Snail
 * @CreateDate: 2022/7/26 16:31
 * @Version: V1.0
 */
@Service
public class FlowInstanceServiceImpl extends FlowServiceFactory implements IFlowInstanceService {

    @Autowired
    private IFlowDefinitionService flowDefinitionService;

    /**
     * 根据流程定义key启动流程实例
     *
     * @return
     */
    @Override
    public ProcessInstance startWorkflowInstanceByDefKey(TaskInitWorkflowDto taskInitWorkflowDto) {
        //根据流程key获取最新的流程定义
        List<FlowProcDefDto> procDefDtos = flowDefinitionService.listFlowProcDefByKey(taskInitWorkflowDto.getProcDefKey());
        if (procDefDtos == null || procDefDtos.isEmpty()) {
            throw new WorkflowException("流程尚未部署！");
        }
        FlowProcDefDto flowProcDefDto = procDefDtos.get(0);
        // 设置流程发起人
        String userId = taskInitWorkflowDto.getUserId();
        if (StringUtils.isBlank(userId)) {
            throw new WorkflowException("流程启初始化失败:流程发起人为空!");
        }
        Map<String, Object> variables = taskInitWorkflowDto.getVariables();
        variables.put(WorkflowConstants.INITIATOR, userId);
        variables.put("_FLOWABLE_SKIP_EXPRESSION_ENABLED", true);
        identityService.setAuthenticatedUserId(userId);
        //启动流程
        return runtimeService.startProcessInstanceById(flowProcDefDto.getId(), variables);
    }
}
